package com.demo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;

@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

	//某个字段为空
	@ExceptionHandler({BindException.class})
	public ResponseEntity<Object> bindExceptionExceptionHandler(BindException e) {
		ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
		return ResponseEntity.ok(objectError.getDefaultMessage());
	}

	@ExceptionHandler({MethodArgumentNotValidException.class})
	public ResponseEntity<Object> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
		ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
		return ResponseEntity.ok(objectError.getDefaultMessage());
	}

	@ExceptionHandler({ValidationException.class})
	public ResponseEntity<Object> methodArgumentNotValidExceptionHandler(ValidationException e) {
		return ResponseEntity.ok(e);
	}

	//列表参数没有传
	@ExceptionHandler({ConstraintViolationException.class})
	public ResponseEntity<Object> methodArgumentNotValidExceptionHandler(ConstraintViolationException e) {
		Set<ConstraintViolation<?>> set = e.getConstraintViolations();
		String result = set.stream().map(ConstraintViolation::getMessage).distinct().findFirst().orElse(null);
		return ResponseEntity.ok(result == null ? "请求参数不能为空" : result);
	}

	//请求参数没有传
	@ExceptionHandler({HttpMessageNotReadableException.class})
	public ResponseEntity<Object> methodArgumentNotValidExceptionHandler(HttpMessageNotReadableException e) {
		log.error("", e);
		return ResponseEntity.ok("请求参数不能为空");
	}
}
